<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="Hexo Theme Redefine">
    
    <meta name="author" content="ChenGreen">
    <!-- preconnect -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    
    
    <!--- Seo Part-->
    
    <link rel="canonical" href="https://chengreen.gitee.io/blog/2024/03/16/内存泄露/"/>
    <meta name="robots" content="index,follow">
    <meta name="googlebot" content="index,follow">
    <meta name="revisit-after" content="1 days">
    
        <meta name="description" content="ASANAddressSanitizer（ASAN）工具是用于用户空间程序的内存错误检测工具，无法直接用于内核空间。 ASAN利用编译器插桩和库来检测程序中是否存在内存的错误访问问题，其能够检测的错误类型包括：  user after free   		使用已释放的内存 heap buffer overflow  	堆内存溢出 stack buffer overflow  	栈访问越界 memor">
<meta property="og:type" content="article">
<meta property="og:title" content="内存泄露">
<meta property="og:url" content="https://chengreen.gitee.io/blog/2024/03/16/%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="ASANAddressSanitizer（ASAN）工具是用于用户空间程序的内存错误检测工具，无法直接用于内核空间。 ASAN利用编译器插桩和库来检测程序中是否存在内存的错误访问问题，其能够检测的错误类型包括：  user after free   		使用已释放的内存 heap buffer overflow  	堆内存溢出 stack buffer overflow  	栈访问越界 memor">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://chengreen.gitee.io/blog/image/%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2/1710639730269.png">
<meta property="og:image" content="https://chengreen.gitee.io/blog/image/%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2/1710639709148.png">
<meta property="og:image" content="https://chengreen.gitee.io/blog/image/%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2/1710639194320.png">
<meta property="og:image" content="https://chengreen.gitee.io/blog/image/%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2/1710639853471.png">
<meta property="article:published_time" content="2024-03-16T14:02:29.000Z">
<meta property="article:modified_time" content="2024-03-17T02:10:22.068Z">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://chengreen.gitee.io/blog/image/%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2/1710639730269.png">
    
    
    <!--- Icon Part-->
    <link rel="icon" type="image/png" href="/blog/images/redefine-favicon.svg" sizes="192x192">
    <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/redefine-favicon.svg">
    <meta name="theme-color" content="#A31F34">
    <link rel="shortcut icon" href="/blog/images/redefine-favicon.svg">
    <!--- Page Info-->
    
    <title>
        
            内存泄露 -
        
        ChenGreen&#39;s Home
    </title>
    
<link rel="stylesheet" href="/blog/css/style.css">

    
<link rel="stylesheet" href="/blog/fonts/fonts.css">

    
<link rel="stylesheet" href="/blog/fonts/Satoshi/satoshi.css">

    
<link rel="stylesheet" href="/blog/fonts/Chillax/chillax.css">

    <!--- Font Part-->
    
    
    
    

    <!--- Inject Part-->
    
    <script id="hexo-configurations">
    let Global = window.Global || {};
    Global.hexo_config = {"hostname":"chengreen.gitee.io","root":"/blog/","language":"en","path":"search.xml"};
    Global.theme_config = {"articles":{"style":{"font_size":"16px","line_height":1.5,"image_border_radius":"14px","image_alignment":"center","image_caption":false,"link_icon":true},"word_count":{"enable":true,"count":true,"min2read":true},"author_label":{"enable":true,"auto":false,"list":[]},"code_block":{"copy":true,"style":"mac","font":{"enable":false,"family":null,"url":null}},"toc":{"enable":true,"max_depth":3,"number":false,"expand":true,"init_open":true},"copyright":false,"lazyload":true,"recommendation":{"enable":false,"title":"推荐阅读","limit":3,"mobile_limit":2,"placeholder":"/images/wallhaven-wqery6-light.webp","skip_dirs":[]}},"colors":{"primary":"#A31F34","secondary":null},"global":{"fonts":{"chinese":{"enable":false,"family":null,"url":null},"english":{"enable":false,"family":null,"url":null}},"content_max_width":"1000px","sidebar_width":"210px","hover":{"shadow":true,"scale":false},"scroll_progress":{"bar":false,"percentage":true},"website_counter":{"url":"https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js","enable":true,"site_pv":true,"site_uv":true,"post_pv":true},"single_page":true,"open_graph":true,"google_analytics":{"enable":false,"id":null}},"home_banner":{"enable":true,"style":"fixed","image":{"light":"/images/wallhaven-wqery6-light.webp","dark":"/images/wallhaven-wqery6-dark.webp"},"title":"ChenGreen's Home","subtitle":{"text":["Loading..."],"hitokoto":{"enable":true,"api":"https://v1.hitokoto.cn"},"typing_speed":100,"backing_speed":80,"starting_delay":500,"backing_delay":1500,"loop":true,"smart_backspace":true},"text_color":{"light":"#fff","dark":"#d1d1b6"},"text_style":{"title_size":"2.8rem","subtitle_size":"1.5rem","line_height":1.2},"custom_font":{"enable":false,"family":null,"url":null},"social_links":{"enable":true,"links":null,"qrs":{"weixin":null}}},"plugins":{"feed":{"enable":false},"aplayer":{"enable":false,"type":"fixed","audios":[{"name":null,"artist":null,"url":null,"cover":null}]},"mermaid":{"enable":false,"version":"9.3.0"}},"version":"2.3.0","navbar":{"auto_hide":false,"color":{"left":"#f78736","right":"#367df7","transparency":35},"links":{"Home":{"path":"/","icon":"fa-regular fa-house"},"Archives":{"path":"/archives","icon":"fa-regular fa-archive"},"Tags":{"path":"/tags","icon":"fa-regular fa-tag"},"Categories":{"path":"/categories","icon":"fa-regular fa-folder"}},"search":{"enable":false,"preload":true}},"page_templates":{"friends_column":2,"tags_style":"blur"},"home":{"sidebar":{"enable":true,"position":"left","first_item":"info","announcement":"Love Yourself","links":{"Archives":{"path":"/archives","icon":"fa-regular fa-archive"},"Tags":{"path":"/tags","icon":"fa-regular fa-tags"},"Categories":{"path":"/categories","icon":"fa-regular fa-folder"}}},"article_date_format":"auto","categories":{"enable":true,"limit":3},"tags":{"enable":true,"limit":3}},"footerStart":"2022/8/17 11:45:14"};
    Global.language_ago = {"second":"%s seconds ago","minute":"%s minutes ago","hour":"%s hours ago","day":"%s days ago","week":"%s weeks ago","month":"%s months ago","year":"%s years ago"};
    Global.data_config = {"masonry":false};
  </script>
    
    <!--- Fontawesome Part-->
    
<link rel="stylesheet" href="/blog/fontawesome/fontawesome.min.css">

    
<link rel="stylesheet" href="/blog/fontawesome/brands.min.css">

    
<link rel="stylesheet" href="/blog/fontawesome/solid.min.css">

    
<link rel="stylesheet" href="/blog/fontawesome/regular.min.css">

    
    
    
    
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
<div class="progress-bar-container">
    

    
        <span class="pjax-progress-bar"></span>
        <span class="swup-progress-icon">
            <i class="fa-solid fa-circle-notch fa-spin"></i>
        </span>
    
</div>


<main class="page-container" id="swup">
    

    

    <div class="main-content-container">
        

        <div class="main-content-header">
            <header class="navbar-container">
    
    <div class="navbar-content">
        <div class="left">
            
            <a class="logo-title" href="/">
                
                ChenGreen&#39;s Home
                
            </a>
        </div>

        <div class="right">
            <!-- PC -->
            <div class="desktop">
                <ul class="navbar-list">
                    
                        
                            <li class="navbar-item">
                                <!-- Menu -->
                                <a class="" 
                                    href="/blog/"  >
                                    
                                        
                                            <i class="fa-regular fa-house"></i>
                                        
                                        HOME
                                    
                                </a>
                                <!-- Submenu -->
                                
                            </li>
                    
                        
                            <li class="navbar-item">
                                <!-- Menu -->
                                <a class="" 
                                    href="/blog/archives"  >
                                    
                                        
                                            <i class="fa-regular fa-archive"></i>
                                        
                                        ARCHIVES
                                    
                                </a>
                                <!-- Submenu -->
                                
                            </li>
                    
                        
                            <li class="navbar-item">
                                <!-- Menu -->
                                <a class="" 
                                    href="/blog/tags"  >
                                    
                                        
                                            <i class="fa-regular fa-tag"></i>
                                        
                                        TAGS
                                    
                                </a>
                                <!-- Submenu -->
                                
                            </li>
                    
                        
                            <li class="navbar-item">
                                <!-- Menu -->
                                <a class="" 
                                    href="/blog/categories"  >
                                    
                                        
                                            <i class="fa-regular fa-folder"></i>
                                        
                                        CATEGORIES
                                    
                                </a>
                                <!-- Submenu -->
                                
                            </li>
                    
                    
                </ul>
            </div>
            <!-- Mobile -->
            <div class="mobile">
                
                <div class="icon-item navbar-bar">
                    <div class="navbar-bar-middle"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Mobile drawer -->
    <div class="navbar-drawer">
        <ul class="drawer-navbar-list">
            
                
                    <li class="drawer-navbar-item flex-center">
                        <a class="" 
                        href="/blog/"  >
                             
                                
                                    <i class="fa-regular fa-house"></i>
                                
                                HOME
                            
                        </a>
                    </li>
                    <!-- Submenu -->
                    
            
                
                    <li class="drawer-navbar-item flex-center">
                        <a class="" 
                        href="/blog/archives"  >
                             
                                
                                    <i class="fa-regular fa-archive"></i>
                                
                                ARCHIVES
                            
                        </a>
                    </li>
                    <!-- Submenu -->
                    
            
                
                    <li class="drawer-navbar-item flex-center">
                        <a class="" 
                        href="/blog/tags"  >
                             
                                
                                    <i class="fa-regular fa-tag"></i>
                                
                                TAGS
                            
                        </a>
                    </li>
                    <!-- Submenu -->
                    
            
                
                    <li class="drawer-navbar-item flex-center">
                        <a class="" 
                        href="/blog/categories"  >
                             
                                
                                    <i class="fa-regular fa-folder"></i>
                                
                                CATEGORIES
                            
                        </a>
                    </li>
                    <!-- Submenu -->
                    
            

        </ul>
    </div>

    <div class="window-mask"></div>

</header>


        </div>

        <div class="main-content-body">

            

            <div class="main-content">

                
                    <div class="post-page-container">
    <div class="article-content-container">

        <div class="article-title">
            
                <h1 class="article-title-regular">内存泄露</h1>
            
            </div>
            
                    
        
        
            <div class="article-header">
                <div class="avatar">
                    <img src="/blog/images/maomao.png">
                </div>
                <div class="info">
                    <div class="author">
                        <span class="name">ChenGreen</span>
                        
                            <span class="author-label">Lv3</span>
                        
                    </div>
                    <div class="meta-info">
                        <div class="article-meta-info">
    <span class="article-date article-meta-item">
        <i class="fa-regular fa-pen-fancy"></i>&nbsp;
        <span class="desktop">2024-03-16 22:02:29</span>
        <span class="mobile">2024-03-16 22:02:29</span>
        <span class="hover-info">Created</span>
    </span>
    
        <span class="article-date article-meta-item">
            <i class="fa-regular fa-wrench"></i>&nbsp;
            <span class="desktop">2024-03-17 10:10:22</span>
            <span class="mobile">2024-03-17 10:10:22</span>
            <span class="hover-info">Updated</span>
        </span>
    

    
    

    
    
    
    
        <span class="article-pv article-meta-item">
            <i class="fa-regular fa-eye"></i>&nbsp;<span id="busuanzi_value_page_pv"></span>
        </span>
    
</div>

                    </div>
                </div>
            </div>
        

        <div class="article-content markdown-body">
            <h1 id="ASAN"><a href="#ASAN" class="headerlink" title="ASAN"></a>ASAN</h1><p>AddressSanitizer（ASAN）工具是用于用户空间程序的内存错误检测工具，无法直接用于内核空间。</p>
<p>ASAN利用编译器插桩和库来检测程序中是否存在内存的错误访问问题，其能够检测的错误类型包括：</p>
<ul>
<li>user after free   		使用已释放的内存</li>
<li>heap buffer overflow  	堆内存溢出</li>
<li>stack buffer overflow  	栈访问越界</li>
<li>memory leaks 		内存泄漏</li>
</ul>
<h2 id="工作原理"><a href="#工作原理" class="headerlink" title="工作原理"></a>工作原理</h2><h3 id="对内存错误访问的检测工作原理"><a href="#对内存错误访问的检测工作原理" class="headerlink" title="对内存错误访问的检测工作原理"></a>对内存错误访问的检测工作原理</h3><p>正常情况下对内存地址的访问方式：</p>
<div class="highlight-container" data-rel="Plaintext"><figure class="iseeu highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">int a = 0xff;</span><br><span class="line">int *address = &amp;a;</span><br><span class="line">*address = a;      //写操作</span><br><span class="line">a = *addreaa;      //读操作</span><br></pre></td></tr></table></figure></div>

<p>ASAN会接管malloc、free函数，不停地查询该内存地址的使用是否合法，实际运行的代码如下形式：</p>
<div class="highlight-container" data-rel="Plaintext"><figure class="iseeu highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">int a = 0xff;</span><br><span class="line">int *address = NULL;</span><br><span class="line">if(IsPoisoned(address))&#123;</span><br><span class="line">    ReportError(address, kAccessSIZE, kIsWrite);</span><br><span class="line">&#125;</span><br><span class="line">*address = a;    //写操作</span><br><span class="line">a = *address；	 //读操作</span><br></pre></td></tr></table></figure></div>

<p>在代码运行期间会对所有的内存访问动作检查，判断其是否 <code>Poisoned</code>。</p>
<p>内存地址在这个过程中被分配成了两段不连续的区域：主内存区域与shadow内存区域。</p>
<p>其中住内存区域也即为代码运行过程中正常使用的内存；shadow内存区域则包含了主内存其余的相关信息，用于判断该区域是否poisoned。</p>
<p>其映射关系为 <code>shadow = (mem &gt;&gt; 3) + offset</code>，也即是8bytes的主内存会映射到1byte的shadow内存。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="/blog/image/%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2/1710639730269.png"
                      alt="1710639730269"
                ></p>
<p>shadow内存共有如下9中状态：</p>
<ul>
<li>负值：当8字节的内存全部被poisoned时</li>
<li>0值：当且仅当8字节的应用内存都没有被poisoned时</li>
<li>正值（1-7）：前k个字节都没有被poisoned时</li>
</ul>
<p>上述状态是由malloc分配内存总是8字节对齐作为前提的。</p>
<p>实际的检测过程是这样的：</p>
<div class="highlight-container" data-rel="Plaintext"><figure class="iseeu highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">*shadow = (char*)(((u_long)addr &gt;&gt; 3)+offset));</span><br><span class="line">/* 当需要访问8bytes大小时 */</span><br><span class="line">if(*shadow)&#123;</span><br><span class="line">    //error</span><br><span class="line">&#125;</span><br><span class="line">/* 当需要访问Nbytes， N = 1，2...7*/)</span><br><span class="line">if(*shadow &amp;&amp; *shadow &lt; ((u_long)addr &amp; 7) + N)&#123;</span><br><span class="line">   //error</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>


<p>假设内存时从8~15的8个bytes，对应的shadow memory的值为5，5&gt;0：</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="/blog/image/%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2/1710639709148.png"
                      alt="1710639709148"
                ></p>
<ul>
<li>从地址x处可以访问的区域有：shadow_memory - (x&amp;7)</li>
<li>从地址8处可以访问的内存区域有：5-（8&amp;7）&#x3D; 5， 即可以访问8，9，10，11，12</li>
<li>从地址9处可以访问的内存区域有：5-（9&amp;7）&#x3D;4，即可以访问9，10，11，12</li>
<li>从地址10处可以访问的内存区域有：5-（10&amp;7）&#x3D;3，即可以访问10，11，12</li>
<li>从地址11处可以访问的内存区域有：5-（11&amp;7）&#x3D;2，即可以访问11，12</li>
<li>从地址12处可以访问的内存区域有：5-（12&amp;7）&#x3D;1，即可以访问12</li>
<li>从地址13处可以访问的内存区域有：5-（13&amp;7）&#x3D; 0，即没有可以访问的地址</li>
<li>从地址14处可以访问的内存区域有：5-（13&amp;7）&lt; 0，即没有可以访问的地址</li>
<li>从地址15处可以访问的内存区域有：5-（13&amp;7）&lt; 0，即没有可以访问的地址</li>
</ul>
<h3 id="内存泄漏工作原理"><a href="#内存泄漏工作原理" class="headerlink" title="内存泄漏工作原理"></a>内存泄漏工作原理</h3><ol>
<li>ASAN会接管内存申请接口，即用户的内存全都由ASAN来管理；</li>
<li>当进程退出时出发ASAN内存泄漏检测或按照一定时间进行内存泄漏检测；</li>
<li>开始内存泄漏检测后，ASAN会遍历当前所有已经分配给用户但没有释放的堆内存，扫描这些内存是否被某个指针引用，这些指针可能时全局变量、局部变量或者是堆里面的指针。如果没有则认为是泄露了；如果内存被引用着，则认为内存没有泄漏；</li>
<li>将所有泄漏的内存信息打印出来，包含内存大小和内存申请的调用栈信息；</li>
</ol>
<h2 id="如何使用"><a href="#如何使用" class="headerlink" title="如何使用"></a>如何使用</h2><p>gcc 4.8以上版本使用ASAN时不需要安装第三方库，通过在编译时指定编译参数即可打开开关，</p>
<div class="highlight-container" data-rel="Plaintext"><figure class="iseeu highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">gcc -fsanitize=address -fno-omit-frame-pointer -O1 -g -o &lt;target_name&gt; &lt;source_name.c&gt;</span><br></pre></td></tr></table></figure></div>

<p><code>-fsanitize=address</code> 开启内存越界检测</p>
<p><code>-fno-omit-frame-pointer</code> 使能栈溢出保护</p>
<p><code>-g</code> 增加有助于debug的信息</p>
<p><code>-O1</code> </p>
<h2 id="log信息分析"><a href="#log信息分析" class="headerlink" title="log信息分析"></a>log信息分析</h2><p><strong>test_user_after_free.c</strong></p>
<div class="highlight-container" data-rel="Plaintext"><figure class="iseeu highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">#include &lt;stdlib.h&gt;</span><br><span class="line"></span><br><span class="line">int main(int argc, char *argv[]) &#123;</span><br><span class="line">  int *p = malloc(sizeof(int));</span><br><span class="line">  free(p);</span><br><span class="line">  return *p;  // 访问了已经释放的内存地址</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>

<p><strong>log信息</strong></p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="/blog/image/%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2/1710639194320.png"
                      alt="1710639194320"
                ></p>
<ol>
<li>内存地址访问错误类型为heap-use-after-free，并给出了地址和寄存器的值</li>
<li>该内存区域在test_user_after_free.c文件的第7行出现错误访问问题</li>
<li>该内存区域在test_use_after_free.c文件的第6行释放</li>
<li>该内存区域在test_use_after_free.c文件的第5行分配</li>
<li>shadow bytes 的数据含义<ol>
<li>int a[8]  &#x3D;&#x3D;&gt;  00 00 00 00</li>
<li>int a[7]  &#x3D;&#x3D;&gt;  00 00 00 04</li>
<li>[ x ]       &#x3D;&#x3D;&gt;  访问出错的内存位置</li>
<li>fd          &#x3D;&#x3D;&gt;   访问出错的类型</li>
</ol>
</li>
</ol>
<h1 id="KASAN"><a href="#KASAN" class="headerlink" title="KASAN"></a>KASAN</h1><p>用于检测内核态存在的内存错误访问</p>
<h2 id="如何使用-1"><a href="#如何使用-1" class="headerlink" title="如何使用"></a>如何使用</h2><p>打开相关配置并重新编译镜像    CONFIG_KASAN&#x3D;y</p>
<h1 id="KMEMLEAK"><a href="#KMEMLEAK" class="headerlink" title="KMEMLEAK"></a>KMEMLEAK</h1><p>内核自带的内核态内存泄漏检测工具，其源码位于 <code>mm/kmemleak.c</code></p>
<p>内存泄漏的根本原因是用户没有释放不再使用的动态申请的内存。</p>
<p>一般来说，没有被指针引用的内存都是不再使用的内存，因为这些内存已经丢失了其地址信息，从而导致内核不能再使用这些内存。</p>
<p><img  
                     lazyload
                     src="/images/loading.svg"
                     data-src="/blog/image/%E5%86%85%E5%AD%98%E6%B3%84%E9%9C%B2/1710639853471.png"
                      alt="1710639853471"
                ></p>
<p>kmemleak通过扫描内存数据，将数据当指针，检测该指针是否被引用，从而判断是否存在内存泄漏的问题。</p>
<h2 id="工作原理-1"><a href="#工作原理-1" class="headerlink" title="工作原理"></a>工作原理</h2><p>当使用申请内存时，内核会把申请到的内存块信息记录下来，用于后续扫描时使用。</p>
<p>内核使用kmemleak-object来记录这些内存块的信息，通过一颗红黑树把这些对象连接起来（使用内存块的地址作为键）</p>
<div class="highlight-container" data-rel="Plaintext"><figure class="iseeu highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">struct kmemleak_object &#123;</span><br><span class="line">    spinlock_t lock;</span><br><span class="line">    unsigned long flags;        /* object status flags */</span><br><span class="line">    struct list_head object_list;</span><br><span class="line">    struct list_head gray_list;</span><br><span class="line">    struct rb_node rb_node;		/*将kmemleak_object连接到红黑树中*/</span><br><span class="line">    ...</span><br><span class="line">    atomic_t use_count;</span><br><span class="line">    unsigned long pointer;		/*记录内存块的起始地址*/</span><br><span class="line">    size_t size;			/*记录内存块的大小*/</span><br><span class="line">    int min_count;			/*用于判断该内存其余是否泄漏*/</span><br><span class="line">    int count;				/*用于判断该内存其余是否泄漏*/</span><br><span class="line">    ...</span><br><span class="line">    pid_t pid;                  /* pid of the current task */</span><br><span class="line">    char comm[TASK_COMM_LEN];   /* executable name */</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></div>


<p>当开启内存泄漏检测时，内核将会创建一个名为 <code>kmemleak</code> 的内核线程来进行检测。通过 <code>kmemleak_object</code>对象中的节点判断是否存在内存泄漏：</p>
<ul>
<li><strong>白色节点</strong> ：表示此对象没有被指针引用（<code>count</code> &lt; <code>min_count</code> ）。</li>
<li><strong>灰色节点</strong> ：表示此对象被一个或多个指针引用（<code>count</code> ≥ <code>min_count</code> ）。</li>
<li><strong>黑色节点</strong> ：表示此对象不需要被扫描（<code>min_count</code> &#x3D; -1），如代码段。</li>
</ul>
<p>当开启内存泄漏检测时，具体检测步骤如下：</p>
<ol>
<li>把所有object的count计数清零，并判断object是否时灰色（默认data、bss、ro_after_init段会被标记为灰色），将灰色object加入灰色链表中</li>
<li>查找指针所引用的内存块是否存在于红黑树中，如果不存在就跳过处理此对象</li>
<li>如果kmemleak_object对象不是白色，则说明已经有指针引用此内存块，跳过处理此对象</li>
<li>如果有对该object的引用，则其count字段进行加一操作，表示有指针引用此内存块</li>
<li>判断当前kmemleak_object对象是否是灰色节点（count≥min_count），如果是，则将其添加到灰色节点链表中</li>
<li>经过上述一系列的扫描，剩余白色object就是可疑的内存泄漏点</li>
</ol>
<h2 id="如何使用KEMELEAK"><a href="#如何使用KEMELEAK" class="headerlink" title="如何使用KEMELEAK"></a>如何使用KEMELEAK</h2><ol>
<li>配置menuconfig<ol>
<li><pre><code>CONFIG_DEBUG_KMEMLEAK = y
<div class="highlight-container" data-rel="Plaintext"><figure class="iseeu highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">2. 使用新的镜像再linux中挂在debugfs文件系统</span><br><span class="line">   1. ```</span><br><span class="line">      mount -t debugfs nodev /sys/kernel/debug/</span><br></pre></td></tr></table></figure></div>
</code></pre>
</li>
</ol>
</li>
<li>加载需要验证的ko文件后使用一下指令检测当前是否存在疑似内存泄漏问题，并查看log<ol>
<li>加载ko文件或执行可执行文件后，需要等待一段时间执行检测指令（否则检测不出内存泄漏问题</li>
<li><pre><code>insmod xxx.ko
./test
echo scan &gt; /sys/kernel/debug/kmemleak
cat /sys/kernel/debug/kmemleak

/*其他参数*/
off 禁用kmemleak（不可逆）
stack=on 启用任务堆栈扫描(default)
stack=off 禁用任务堆栈扫描
scan=on 启动自动记忆扫描线程(default)
scan=off 停止自动记忆扫描线程
scan=&lt;secs&gt; 设置n秒内自动记忆扫描，默认600s
scan 开启内核扫描
clear 清除内存泄露报告
dump=&lt;addr&gt; 转存信息对象在&lt;addr&gt;
<div class="highlight-container" data-rel="Plaintext"><figure class="iseeu highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">4. 需要清空log使用以下指令</span><br><span class="line">   1. ```</span><br><span class="line">      echo clear &gt; /sys/kernel/debug/kmemleak</span><br></pre></td></tr></table></figure></div>

建议在Linux启动后未加载测试模块前线执行下述指令清除linux启动过程中出现的疑似内存泄漏问题
</code></pre>
</li>
<li><pre><code>echo scan &gt; /sys/kernel/debug/kmemleak
echo clear &gt; /sys/kernel/debug/kmemleak
</code></pre>
</li>
</ol>
</li>
</ol>
<h3 id="使用tips"><a href="#使用tips" class="headerlink" title="使用tips"></a>使用tips</h3><p>kmemleak的扫描算法中存在误报的可能</p>
<ul>
<li>内存中有个数据与rbtree中的某个地址相同，当其为数据而非指针，造成误报，未检测该处内存泄漏</li>
<li>rbtree中某个地址在内存中找不到，但程序可能还在用，只是因为程序并没有直接保存访问地址，而是通过某种方式临时计算访问地址，造成误报该处存在内存泄漏</li>
<li>扫描时间长短取决于内核内存使用量</li>
<li>建议在系统处于空间状态下进行扫墓哎操作，以减少误报和干扰</li>
<li>建议执行可执行文件后，rmmod ko模块再进行检测，避免全局变量存在造成误报</li>
<li>kmemleak只能检测到堆分配的内存泄漏，对于其他类型的资源泄漏（如文件描述符、锁等），无法提供完整的信息</li>
</ul>

        </div>

        

        

        

        
            <div class="article-nav">
                
                
                    <div class="article-next">
                        <a class="next"
                        rel="next"
                        href="/blog/2024/03/03/C%E8%AF%AD%E8%A8%80%E5%89%96%E6%9E%90/"
                        >
                            <span class="title flex-center">
                                <span class="post-nav-title-item">C语言剖析</span>
                                <span class="post-nav-item">Next posts</span>
                            </span>
                            <span class="right arrow-icon flex-center">
                                <i class="fa-solid fa-chevron-right"></i>
                            </span>
                        </a>
                    </div>
                
            </div>
        


        
            <div class="comment-container">
                <div class="comments-container pjax">
    <div id="comment-anchor"></div>
    <div class="comment-area-title">
        <i class="fa-solid fa-comments"></i>&nbsp;Comments
    </div>
    

        
            
 
    <div id="waline"></div>
    <script type="module"  data-swup-reload-script>
        import { init } from 'https://evan.beee.top/js/waline.mjs';

        function loadWaline() {
            init({
                el: '#waline',
                serverURL: 'https://example.example.com',
                lang: 'zh-CN',
                dark: 'body[class~="dark-mode"]',
                requiredMeta: ['nick','mail'], // cannot customize by theme config, change it yourself
            });
        }

        if ('true') {
            const loadWalineTimeout = setTimeout(() => {
                loadWaline();
                clearTimeout(loadWalineTimeout);
            }, 1000);
        } else {
            window.addEventListener('DOMContentLoaded', loadWaline);
        }
        
    </script>



        
    
</div>

            </div>
        
    </div>

    
        <div class="toc-content-container">
            <div class="post-toc-wrap">
    <div class="post-toc">
        <div class="toc-title">On this page</div>
        <div class="page-title">内存泄露</div>
        <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#ASAN"><span class="nav-text">ASAN</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86"><span class="nav-text">工作原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AF%B9%E5%86%85%E5%AD%98%E9%94%99%E8%AF%AF%E8%AE%BF%E9%97%AE%E7%9A%84%E6%A3%80%E6%B5%8B%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86"><span class="nav-text">对内存错误访问的检测工作原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86"><span class="nav-text">内存泄漏工作原理</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8"><span class="nav-text">如何使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#log%E4%BF%A1%E6%81%AF%E5%88%86%E6%9E%90"><span class="nav-text">log信息分析</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#KASAN"><span class="nav-text">KASAN</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8-1"><span class="nav-text">如何使用</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#KMEMLEAK"><span class="nav-text">KMEMLEAK</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86-1"><span class="nav-text">工作原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8KEMELEAK"><span class="nav-text">如何使用KEMELEAK</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8tips"><span class="nav-text">使用tips</span></a></li></ol></li></ol></li></ol>

    </div>
</div>
        </div>
    
</div>



                

            </div>
            
            

        </div>

        <div class="main-content-footer">
            <footer class="footer">
    <div class="info-container">
        <div class="copyright-info">
            &copy;
            
              <span>2022</span>
              -
            
            2024&nbsp;&nbsp;<i class="fa-solid fa-heart fa-beat" style="--fa-animation-duration: 0.5s; color: #f54545"></i>&nbsp;&nbsp;<a href="/">ChenGreen</a>
        </div>
        
            <script data-swup-reload-script src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
            <div class="website-count info-item">
                
                    <span id="busuanzi_container_site_uv" class="busuanzi_container_site_uv">
                        VISITOR COUNT&nbsp;<span id="busuanzi_value_site_uv" class="busuanzi_value_site_uv"></span>
                    </span>
                
                
                    <span id="busuanzi_container_site_pv" class="busuanzi_container_site_pv">
                        TOTAL PAGE VIEWS&nbsp;<span id="busuanzi_value_site_pv" class="busuanzi_value_site_pv"></span>
                    </span>
                
            </div>
        
        <div class="theme-info info-item">
            <span class="powered-by-container">POWERED BY <?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg version="1.1" id="圖層_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1rem" height="1rem" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"><path fill="#0E83CD" d="M256.4,25.8l-200,115.5L56,371.5l199.6,114.7l200-115.5l0.4-230.2L256.4,25.8z M349,354.6l-18.4,10.7l-18.6-11V275H200v79.6l-18.4,10.7l-18.6-11v-197l18.5-10.6l18.5,10.8V237h112v-79.6l18.5-10.6l18.5,10.8V354.6z"/></svg><a target="_blank" href="https://hexo.io">Hexo</a></span>
                <br>
            <span class="theme-version-container">THEME&nbsp;<a class="theme-version" target="_blank" href="https://github.com/EvanNotFound/hexo-theme-redefine">Redefine v2.3.0</a></span>
        </div>
        
        
        
        
        
        
    </div>  
</footer>
        </div>
    </div>

    
        <div class="post-tools">
            <div class="post-tools-container">
    <ul class="article-tools-list">
        <!-- TOC aside toggle -->
        
            <li class="right-bottom-tools page-aside-toggle">
                <i class="fa-regular fa-outdent"></i>
            </li>
        

        <!-- go comment -->
        
            <li class="go-comment">
                <i class="fa-regular fa-comments"></i>
            </li>
        
    </ul>
</div>

        </div>
    

    <div class="right-side-tools-container">
        <div class="side-tools-container">
    <ul class="hidden-tools-list">
        <li class="right-bottom-tools tool-font-adjust-plus flex-center">
            <i class="fa-regular fa-magnifying-glass-plus"></i>
        </li>

        <li class="right-bottom-tools tool-font-adjust-minus flex-center">
            <i class="fa-regular fa-magnifying-glass-minus"></i>
        </li>

        <li class="right-bottom-tools tool-expand-width flex-center">
            <i class="fa-regular fa-expand"></i>
        </li>

        <li class="right-bottom-tools tool-dark-light-toggle flex-center">
            <i class="fa-regular fa-moon"></i>
        </li>

        <!-- rss -->
        

        

        <li class="right-bottom-tools tool-scroll-to-bottom flex-center">
            <i class="fa-regular fa-arrow-down"></i>
        </li>
    </ul>

    <ul class="visible-tools-list">
        <li class="right-bottom-tools toggle-tools-list flex-center">
            <i class="fa-regular fa-cog fa-spin"></i>
        </li>
        
            <li class="right-bottom-tools tool-scroll-to-top flex-center">
                <i class="arrow-up fas fa-arrow-up"></i>
                <span class="percent"></span>
            </li>
        
        
    </ul>
</div>

    </div>

    <div class="image-viewer-container">
    <img src="">
</div>


    


</main>


<script src="/blog/js/libs/Swup.min.js"></script>

<script src="/blog/js/libs/SwupSlideTheme.min.js"></script>

<script src="/blog/js/libs/SwupScriptsPlugin.min.js"></script>

<script src="/blog/js/libs/SwupProgressPlugin.min.js"></script>

<script src="/blog/js/libs/SwupScrollPlugin.min.js"></script>

<script>
    const swup = new Swup({
        plugins: [
            new SwupScriptsPlugin({
                optin: true,
            }),
            new SwupProgressPlugin(),
            new SwupScrollPlugin({
                offset: 80,
            }),
            new SwupSlideTheme({
                mainElement: ".main-content-body",
            }),
        ],
        containers: ["#swup"],
    });

    swup.on("pageView", () => {
        Global.refresh();
    });

    // if (document.readyState === "complete") {
    //
    // } else {
    //     document.addEventListener("DOMContentLoaded", () => init());
    // }
</script>





<script src="/blog/js/utils.js"></script>

<script src="/blog/js/main.js"></script>

<script src="/blog/js/layouts/navbarShrink.js"></script>

<script src="/blog/js/tools/scrollTopBottom.js"></script>

<script src="/blog/js/tools/lightDarkSwitch.js"></script>

<script src="/blog/js/layouts/categoryList.js"></script>





    
<script src="/blog/js/tools/codeBlock.js"></script>




    
<script src="/blog/js/layouts/lazyload.js"></script>






  
<script src="/blog/js/libs/Typed.min.js"></script>

  
<script src="/blog/js/plugins/typed.js"></script>







<div class="post-scripts" data-swup-reload-script>
    
        
<script src="/blog/js/tools/tocToggle.js"></script>

<script src="/blog/js/layouts/toc.js"></script>

<script src="/blog/js/libs/anime.min.js"></script>

<script src="/blog/js/plugins/tabs.js"></script>

    
</div>


</body>
</html>
